package cn.ljl.user.service.impl;

import cn.ljl.basic.exception.BusinessException;
import cn.ljl.basic.util.*;
import cn.ljl.user.constant.WxConstants;
import cn.ljl.user.domain.Logininfo;
import cn.ljl.user.domain.User;
import cn.ljl.user.domain.Wxuser;
import cn.ljl.user.dto.LoginDto;
import cn.ljl.user.mapper.LogininfoMapper;
import cn.ljl.user.mapper.UserMapper;
import cn.ljl.user.mapper.WxuserMapper;
import cn.ljl.user.service.ILogininfoService;
import cn.ljl.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
@Autowired
private LogininfoMapper logininfoMapper;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private WxuserMapper wxuserMapper;
@Autowired
private UserMapper userMapper;
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //1.校验空值
        if(StringUtils.isEmpty(loginDto.getAccount()) || StringUtils.isEmpty(loginDto.getCheckPass()) ){
            throw new BusinessException("信息不能为空!!!");
        }
        //2.校验账号
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if(logininfo==null){//根据账号没有查询到信息
            throw new BusinessException("账号错误!!!");
        }
        //3.校验密码
        String inputMd5Pwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
        if(!inputMd5Pwd.equals(logininfo.getPassword())){
            throw new BusinessException("密码错误!!!");
        }
        //4.校验是否禁用
        if(!logininfo.getDisable()){
            throw new BusinessException("该账号被禁用，请联系管理员!!!");
        }
        //5.将登录信息保存在redis，30分钟有效。key随机生成
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,3, TimeUnit.MINUTES);
        //6.返回信息1.key - 后续每次发送请求都要携带这个key，用于判断是否登录了2.登录信息 - 在前端页面显示账号
        HashMap<String, Object> map = new HashMap<>();
        logininfo.setSalt(null);
        logininfo.setPassword(null);

        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;
    }

    @Override
    public AjaxResult wechatLogin(Map<String, String> map) {
        //发送第二个请求：需要什么code，appid，secret?返回什么？token,openid
        //1准备第二个请求地址
        String url= WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",map.get("code"));
        //2使用HttpUtil发送微信登录请求：第二个请求，返回json格式字符串
        String jsonStr = HttpUtil.httpGet(url);
        //3.通过fastjson将json格式的字符串转成json对象为了获取token和openid
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        String access_token = jsonObj.getString("access_token");
        String openid = jsonObj.getString("openid");
        //4.通过openid查t_wxuser表
        Wxuser wxuser= wxuserMapper.loadByOpengid(openid);
        //4.1查到了-以前扫码过-免密登录，返回true，token和logininfo对象
        if (wxuser!=null){
            User user = userMapper.loadById(wxuser.getUserId());

            if (user!=null){//免密登录
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
                String token = UUID.randomUUID().toString();
                redisTemplate.opsForValue().set(token,logininfo,3, TimeUnit.MINUTES);
                //6.返回信息1.key - 后续每次发送请求都要携带这个key，用于判断是否登录了2.登录信息 - 在前端页面显示账号
                HashMap<String, Object> resultMap = new HashMap<>();
                //响应给前端：将盐值和密码置空，提高安全性
                logininfo.setSalt(null);
                logininfo.setPassword(null);

                resultMap.put("token",token);
                resultMap.put("logininfo",logininfo);
                return AjaxResult.me().setObj(resultMap);}


        }
        //4.2.没有查询到 - 第一次扫码 - 把token和openid响应给前端 - 到绑定页面进行绑定

        return AjaxResult.me().setSuccess(false).setObj("?access_token="+access_token+"&openid"+openid);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //1.校验-空值
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空");
        }
         //2.校验-手机验证码：是否过期，是否正确
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if(obj==null){
            throw new BusinessException("验证码过期");
        }
        if (verifyCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("手机验证码错误");
        }

        //3.准备第三个请求
        String url = WxConstants.GET_ACK_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        //4.使用HttpUtil发送微信绑定请求 - 获取微信用户信息：返回jsonStr
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson处理jsonStr - 将jsonObj中的数据转换WxUser对象
        Wxuser wxuser= jsonStr2WxUser(jsonStr);
         //6.创建User对象和Logininfo对象【phone】 - 难度
        User user = userMapper.loadByPhone(phone);
        if (user==null){
            user=phone2User(phone);
            Logininfo newLogininfo=user2Logininfo(user);
            logininfoMapper.save(newLogininfo);
            user.setLogininfoId(newLogininfo.getId());
            userMapper.save(user);


        }
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        //7.添加数据库：Logininfo对象 - User对象 - WxUser对象
         //8.做免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,3, TimeUnit.MINUTES);
        //6.返回信息1.key - 后续每次发送请求都要携带这个key，用于判断是否登录了2.登录信息 - 在前端页面显示账号
        HashMap<String, Object> resultMap = new HashMap<>();
        //响应给前端：将盐值和密码置空，提高安全性
        logininfo.setSalt(null);
        logininfo.setPassword(null);

        resultMap.put("token",token);
        resultMap.put("logininfo",logininfo);
        return AjaxResult.me().setObj(resultMap);


    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(12);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);

        return user;
    }

    private Wxuser jsonStr2WxUser(String jsonStr) {
        JSONObject obj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(obj.getString("obj"));
        wxuser.setNickname(obj.getString("nickname"));
        wxuser.setHeadimgurl(obj.getString("headimgurl"));
        wxuser.setUnionid(obj.getString("unionid"));

        return wxuser;
    }
}
